<?php


namespace app\console\service\category;

use app\dao\goods\CategoryDao;
use app\model\Category;

class CategoryService
{
    /**
     * @var Category
     */
    private Category $category;

    public function __construct(Category $category)
    {
        $this->category = $category ;
    }

    public function create($data)
    {
        $categoryDao = new CategoryDao();
        $level = $categoryDao->getLevelByParentId($data['parent_id']);

        return $categoryDao->save([
            'name' => $data['name'],
            'number' => $data['number'],
            'type' => $data['type'],
            'tags' => json_encode($data['tags']),
            'parent_id' => $data['parent_id'],
            'level' => empty($level->level) ? 1 : $level->level + 1,
            'ratio' => $data['ratio'],
        ]);
    }

    public function update($data)
    {
        $categoryDao = new CategoryDao();

        if (!empty($data['name']))
        {
            $this->category->name = $data['name'];
        }
        if (!empty($data['tags']))
        {
            $this->category->tags = json_encode($data['tags']);
        }
        if (!empty($data['ratio']))
        {
            $this->category->ratio = $data['ratio'];
        }

        return $categoryDao->update($this->category->toArray(), $this->category->id);
    }

    public function delete()
    {
        $categoryDao = new CategoryDao();
        $categoryDao->deleteByid($this->category->id);
    }



}